<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="false" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库状态" prop="receiptOrderStatus">
              <el-radio-group v-model="queryParams.orderStatus" @change="handleQuery">
                <el-radio-button
                    :key="-2"
                    :label="-2"
                >
                  全部
                </el-radio-button>
                <el-radio-button
                    v-for="item in wms_receipt_status"
                    :key="item.value"
                    :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库类型" prop="optType">
              <el-radio-group v-model="queryParams.optType" @change="handleQuery">
                <el-radio-button
                    :key="-1"
                    :label="-1"
                >
                  全部
                </el-radio-button>
                <el-radio-button
                    v-for="item in wms_receipt_type"
                    :key="item.value"
                    :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="orderNo">
              <el-input
                  v-model="queryParams.orderNo"
                  placeholder="请输入入库单号"
                  clearable
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="mt20">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">入库单据</span></el-col>
        <el-col :span="1.5">
          <el-button
              type="primary"
              @click="handleAdd"
          >新增入库单
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="headerList" border class="mt20" width ="100%" height="calc(100vh - 320px)">
        <!-- 单据明细 -->
        <el-table-column type="expand" width="40">
          <template #default="{ row }">
            <div style="padding: 0 50px 20px 50px">
              <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
                <el-col :span="6"><span style="font-size: large">单据明细</span></el-col>
              </el-row>
              <!-- 现在直接使用 row.inDetailList 展示明细数据 -->
              <el-table :data="row.inDetailList || []" border>
                <el-table-column show-overflow-tooltip type="index" label="行号" align="center"></el-table-column>
                <el-table-column show-overflow-tooltip prop="drugId" label="药品编码" align="center" width="150"/>
                <el-table-column show-overflow-tooltip prop="drugName" label="药品名称" align="center" width="300"/>
                <el-table-column show-overflow-tooltip prop="drugCd" label="生产厂家" align="center"/>
                <el-table-column show-overflow-tooltip prop="drugPZWH" label="批准文号" align="center" width="150"/>
                <el-table-column show-overflow-tooltip prop="drugGg" label="规格" align="center" width="200"/>
                <el-table-column show-overflow-tooltip prop="drugDw" label="单位" align="center" width="80"/>
                <el-table-column show-overflow-tooltip prop="drugNum" label="数量" align="center" width="80"/>
<!--                <el-table-column show-overflow-tooltip prop="drugCheckNum" label="确认数量" align="center" width="100"/>-->
<!--                <el-table-column show-overflow-tooltip prop="drugBatchNo" label="批号" align="center" width="120"/>-->
<!--                <el-table-column show-overflow-tooltip prop="drugPd" label="生产日期" align="center" width="120"/>-->
<!--                <el-table-column show-overflow-tooltip prop="drugExp" label="有效期" align="center" width="120"/>-->
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="billsId" label="单据号" align="center"
                         width="200"></el-table-column>
        <el-table-column show-overflow-tooltip prop="billsTypeName" label="单据类型" align="center" width="120"></el-table-column>
        <el-table-column show-overflow-tooltip prop="billsCdName" label="往来单位" align="center" width="250"></el-table-column>
        <el-table-column show-overflow-tooltip prop="totalPackages" label="总件数" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="totalQuantity" label="总数量" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip label="单据状态" align="center" width="130">
          <template #default="scope">
            <el-tag v-if="scope.row.billsState === '0'" type="info">未收货</el-tag>
            <el-tag v-else-if="scope.row.billsState === '1'" type="warning">已收货</el-tag>
            <el-tag v-else-if="scope.row.billsState === '2'" type="primary">已验收</el-tag>
            <el-tag v-else-if="scope.row.billsState === '3'" type="success">已上架</el-tag>
            <el-tag v-else-if="scope.row.billsState === '4'" type="danger">已作废</el-tag>
            <el-tag v-else>未知状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="creatorName" label="制单人" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="制单时间" align="center" width="160"></el-table-column>
        <el-table-column label="操作" align="center" width="450">
          <template #default="scope">
            <!-- 状态为0-未收货时：可以修改、可以作废、可以提取，不能签字 -->
            <el-button v-if="scope.row.billsState === '0'" type="primary" size="small" @click="handleExtract(scope.row)">提取</el-button>
            <el-button v-if="scope.row.billsState === '0'" type="warning" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button v-if="scope.row.billsState === '0'" type="danger" size="small" @click="handleCancel(scope.row)">作废</el-button>

            <!-- 状态为1-已收货时：不能签字、不能作废、不能修改，可以PDA完成、可以拒收 -->
            <el-button v-if="scope.row.billsState === '1'" type="success" size="small" @click="handlePdaComplete(scope.row)">PDA完成</el-button>
            <el-button v-if="scope.row.billsState === '1'" type="danger" size="small" @click="handleReject(scope.row)">拒收</el-button>

            <!-- 状态为2-已验收时：可以签字，不能作废、不能修改 -->
            <el-button v-if="scope.row.billsState === '2'" type="success" size="small" @click="handleSign(scope.row)">签字</el-button>

            <!-- 状态为3-已上架时：不能作废、不能修改，只能查看 -->
            <!-- 状态为4-已作废时：除了查看，别的不显示 -->
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float: right; margin: 20px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                       :page-sizes="[10, 50, 100]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
import {
  buyStoreList,//获取列表
  extractBills,//提取单据
  pdaCompleted,//PDA完成
  signBills,//签字
  cancelBills,//作废
  rejectGoods,//拒收
} from '@/api/storage/buyStore'
export default {
  data() {
    return {
      total: 0,
      pageSize: 10,
      pageNum: 1,
      queryParams: {
        orderNo: '',//入库单号
        orderStatus: "buyStore",//验收管理
        optType: -1,//收货
      },
      wms_receipt_status: [
        {
          label: '未收货',
          value: '0'
        },
        {
          label: '已收货',
          value: '1'
        },
        {
          label: '异常',
          value: '4'
        },
        {
          label: '作废',
          value: '5'
        }
      ],//入库状态（收货管理只显示收货相关状态）
      wms_receipt_type: [
        { label: '采购入库', value: 'PurchaseWareHouseIn'},
        { label: '生产入库', value: 'ProduceWareHouseIn'},
        { label: '退货入库', value: 'ReturnWareHouseIn'},
        { label: '调拨入库', value: 'AllocateWareHouseIn'},
        { label: '赠品入库', value: 'GiftHouseIn'},
        { label: '其他入库', value: 'OtherHouseIn'}
      ],//入库类型
      headerList: [],//table的数据
    }
  },
  created() {
    this.handleQuery();
  },
  methods: {
    //提取单据操作
    handleExtract(row) {
      this.$confirm('确定要提取该入库单据吗？', '提取确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        extractBills(row.billsId).then(res => {
          this.$message.success('提取成功');
          this.handleQuery(); // 刷新列表
        }).catch(err => {
          this.$message.error('提取失败：' + err.message);
        })
      })
    },
    //PDA完成操作
    handlePdaComplete(row) {
      this.$confirm('确定要完成PDA操作吗？', 'PDA完成确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        pdaCompleted(row.billsId).then(res => {
          this.$message.success('PDA完成成功');
          this.handleQuery(); // 刷新列表
        }).catch(err => {
          this.$message.error('PDA完成失败：' + err.message);
        })
      })
    },
    //签字操作
    handleSign(row) {
      this.$confirm('确定要签字该入库单据吗？签字后将会进行库存操作！', '签字确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取当前用户信息
        const currentUser = this.$store.getters.name || '系统管理员';
        signBills(row.billsId, currentUser, currentUser).then(res => {
          this.$message.success('签字成功，库存已更新');
          this.handleQuery(); // 刷新列表
        }).catch(err => {
          this.$message.error('签字失败：' + err.message);
        })
      })
    },
    //作废操作
    handleCancel(row) {
      this.$prompt('请输入作废原因', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '作废原因不能为空'
      }).then(({ value }) => {
        console.log('作废请求参数:', { billsId: row.billsId, reason: value });
        cancelBills(row.billsId, value).then(res => {
          console.log('作废响应:', res);
          this.$message.success('作废成功');
          this.handleQuery(); // 刷新列表
        }).catch(err => {
          console.error('作废失败:', err);
          this.$message.error('作废失败：' + (err.response?.data?.msg || err.message));
        })
      })
    },

    //拒收操作
    handleReject(row) {
      this.$prompt('请输入拒收原因', '拒收', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '拒收原因不能为空'
      }).then(({ value }) => {
        console.log('拒收请求参数:', { billsId: row.billsId, reason: value });
        rejectGoods(row.billsId, value).then(res => {
          console.log('拒收响应:', res);
          this.$message.success('拒收成功');
          this.handleQuery(); // 刷新列表
        }).catch(err => {
          console.error('拒收失败:', err);
          this.$message.error('拒收失败：' + (err.response?.data?.msg || err.message));
        })
      })
    },

    //编辑
    handleEdit(row) {
      this.$router.push({
        path: "/storage/buyStore/qmsDocument",
        query: {
          billsId: row.billsId
        }
      });
    },
    //重置
    resetQuery() {
      this.queryParams = {
        orderNo: '',//入库单号
        orderStatus: "buyStore",//入库状态
        optType: -1,//入库类型
      }
      this.handleQuery();
    },
    //查询
    handleQuery() {
      buyStoreList(this.queryParams).then(res=>{
        this.headerList = res.rows;
        this.total = res.total;
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/storage/buyStore/qmsDocument",
      });
    },
    // 页大小变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.pageNum = 1; // 重置为第一页
    },

    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
    },
  },
}
</script>
